package com.ed.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ed.context.UserContext;
import com.ed.domain.Hama;
import com.ed.domain.Option;
import com.ed.dto.AnswerQDTO;
import com.ed.dto.SubmitDto;
import com.ed.mapper.IHamaQuestionMapper;
import com.ed.service.IFaqQuestionService;
import com.ed.service.IHamaQuestionService;
import com.ed.task.AnswerQuesTask;
import com.ed.vo.QuesVO;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HamaQuestionServiceImpl extends ServiceImpl<IHamaQuestionMapper, Hama> implements IHamaQuestionService {
    @Autowired
    private IHamaQuestionMapper HamaMapper;
    @Autowired
    private AnswerQuesTask answerQuesTask;
    @Resource
    private IFaqQuestionService iFaqQuestionService;


    @Override
    public void AddHama(Hama hama) {
        save(hama);
    }

    @Override
    public void DeleteHama(Integer id) {
        removeById(id);
    }

    @Override
    public void UpdateHama(Hama hama) {
        updateById(hama);
    }

    @Override
    public QuesVO getHama(Integer id) {
        Hama hama = getById(id);
        // TODO 查询选项
        if (hama != null) {
            QuesVO quesVO = new QuesVO();
            quesVO.setType(hama.getType());
            quesVO.setQuestion(hama.getTitle());
            return quesVO;
        }
        return null;
    }

    @Override
    public List<QuesVO> getHamas() {
        List<QuesVO> hamas = HamaMapper.getHamas();
        return hamas;
    }

    public static final String HAMA_CALCULATESCORE = "hama_calculateScore_";

    @Override
    public Integer calculateScore(SubmitDto submitDto) {
        List<AnswerQDTO> answerQDTOS = submitDto.getAnswerQDTOS();
        String idempotentKey = HAMA_CALCULATESCORE + UserContext.getCurrentUser();
        iFaqQuestionService.checkAndRecordIdempotent(idempotentKey);
        Integer score = 0;
        for (AnswerQDTO answerQDTO : answerQDTOS) {
            if (answerQDTO.getOptionIndex() != null) {
                Integer index = answerQDTO.getOptionIndex();
                Option option = answerQDTO.getOption().get(index);
                score += option.getWeight();
            }
        }
        answerQuesTask.recordHama(answerQDTOS, score, UserContext.getCurrentUser(),submitDto.getStartTime());
        return score;
    }
}
